{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c1ede8c3",
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "import h5py\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "import matplotlib.image as mpimg\n",
    "import os\n",
    "import os.path as osp\n",
    "import imageio.v2 as imageio\n",
    "import cv2\n",
    "\n",
    "from scipy.stats import describe"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "899a56cc",
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "import re\n",
    "import cv2\n",
    "\n",
    "\n",
    "def load_pfm_file(file_path):\n",
    "    with open(file_path, \"rb\") as file:\n",
    "        header = file.readline().decode(\"UTF-8\").strip()\n",
    "\n",
    "        if header == \"PF\":\n",
    "            is_color = True\n",
    "        elif header == \"Pf\":\n",
    "            is_color = False\n",
    "        else:\n",
    "            raise ValueError(\"The provided file is not a valid PFM file.\")\n",
    "\n",
    "        dimensions = re.match(r\"^(\\d+)\\s(\\d+)\\s$\", file.readline().decode(\"UTF-8\"))\n",
    "        if dimensions:\n",
    "            img_width, img_height = map(int, dimensions.groups())\n",
    "        else:\n",
    "            raise ValueError(\"Invalid PFM header format.\")\n",
    "\n",
    "        endian_scale = float(file.readline().decode(\"UTF-8\").strip())\n",
    "        if endian_scale < 0:\n",
    "            dtype = \"<f\"  # little-endian\n",
    "        else:\n",
    "            dtype = \">f\"  # big-endian\n",
    "\n",
    "        data_buffer = file.read()\n",
    "        img_data = np.frombuffer(data_buffer, dtype=dtype)\n",
    "\n",
    "        if is_color:\n",
    "            img_data = np.reshape(img_data, (img_height, img_width, 3))\n",
    "        else:\n",
    "            img_data = np.reshape(img_data, (img_height, img_width))\n",
    "\n",
    "        img_data = cv2.flip(img_data, 0)\n",
    "\n",
    "    return img_data\n",
    "def _load_pose(path, ret_44=False):\n",
    "    f = open(path)\n",
    "    RT = np.loadtxt(f, skiprows=1, max_rows=4, dtype=np.float32)\n",
    "    assert RT.shape == (4, 4)\n",
    "    RT = np.linalg.inv(RT)  # world2cam to cam2world\n",
    "\n",
    "    K = np.loadtxt(f, skiprows=2, max_rows=3, dtype=np.float32)\n",
    "    assert K.shape == (3, 3)\n",
    "\n",
    "    if ret_44:\n",
    "        return K, RT\n",
    "    return K, RT[:3, :3], RT[:3, 3]  # , depth_uint8_to_f32"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f96de6ed",
   "metadata": {},
   "outputs": [],
   "source": [
    "root = \"/lc/data/3D/eth3d/eth3d/playground/images/images_rig_cam4_undistorted/1477833684658155598.png\"\n",
    "path = f\"{root}\"\n",
    "img = mpimg.imread(root)\n",
    "# depth = load_pfm_file(path)\n",
    "# print(depth.shape)\n",
    "# print(describe(depth, axis=None))\n",
    "print(img.shape)\n",
    "print(describe(img, axis=None))\n",
    "# (518, 917, 3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3346e278",
   "metadata": {},
   "outputs": [],
   "source": [
    "for i in range(3):\n",
    "    print(describe(img[:, :, i], axis=None))\n",
    "print(describe(img[:, :, 0] - img[:, :, 1], axis=None))\n",
    "print(describe(img[:, :, 0] - img[:, :, 2], axis=None))\n",
    "# DescribeResult(nobs=494088, minmax=(np.float32(0.0), np.float32(0.99215686)), mean=np.float32(0.29604754), variance=np.float64(0.04928892023271152), skewness=np.float64(1.9245723485946655), kurtosis=np.float32(3.031291))\n",
    "# DescribeResult(nobs=494088, minmax=(np.float32(0.0), np.float32(0.0)), mean=np.float32(0.0), variance=np.float64(0.0), skewness=np.float64(nan), kurtosis=np.float32(nan))\n",
    "# all 3 channels are same"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6bfed4bc",
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "s = 0\n",
    "# List of file paths\n",
    "root = \"/lc/data/3D/eth3d/eth3d/terrains/images/images_rig_cam5_undistorted\"\n",
    "file_paths = sorted([f for f in os.listdir(root) if f.endswith(\".png\")])\n",
    "\n",
    "cols = 2\n",
    "rows = 5\n",
    "interval = 3\n",
    "# Create a figure with 2 columns and 10 rows,dpi=100\n",
    "fig, axs = plt.subplots(rows, cols, figsize=(12, rows*3))\n",
    "\n",
    "# Iterate over the file paths and display the images\n",
    "for i, file_path in enumerate(file_paths[s:rows*cols*interval//2+s:interval]):\n",
    "    img = mpimg.imread(osp.join(root, file_path))\n",
    "    depth = load_pfm_file(osp.join(root.removesuffix('_undistorted').replace('images/', 'depths/'), file_path.replace(\"png\",\"pfm\")))\n",
    "    desc = f'{depth.min()}, {depth.max()}, {depth.mean()}'\n",
    "    axs[i * 2 // cols , i * 2 % cols ].imshow(img)\n",
    "    axs[i * 2 // cols , i * 2 % cols].axis(\"off\")  # Hide axis ticks\n",
    "    axs[i * 2 // cols , i * 2 % cols].set_title(file_path+f\"_{i}\")\n",
    "    axs[i * 2 // cols , i * 2 % cols + 1].imshow(depth)\n",
    "    axs[i * 2 // cols , i * 2 % cols + 1].axis(\"off\")  # Hide axis ticks\n",
    "    axs[i * 2 // cols , i * 2 % cols + 1].set_title(desc)\n",
    "\n",
    "plt.show()\n",
    "print(img.shape)\n",
    "# (519, 952, 3)\n",
    "# dark, 3 channels are same"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5bfaf6f0",
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "print(img.shape)\n",
    "print(depth.shape, depth.dtype) \n",
    "print(describe(depth, axis=None))\n",
    "# (512, 640, 3)\n",
    "# (128, 160) float32\n",
    "# DescribeResult(nobs=20480, minmax=(np.float32(0.0), np.float32(946.78094)), mean=np.float32(431.71103), variance=np.float64(104223.69060989306), skewness=np.float64(-0.42943912744522095), kurtosis=np.float32(-1.4890113))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2616181c",
   "metadata": {},
   "outputs": [],
   "source": [
    "# extrinsic\n",
    "# 0.970263 0.00747983 0.241939 -191.02\n",
    "# -0.0147429 0.999493 0.0282234 3.28832\n",
    "# -0.241605 -0.030951 0.969881 22.5401\n",
    "# 0.0 0.0 0.0 1.0\n",
    "\n",
    "# intrinsic\n",
    "# 361.54125 0.0 82.900625\n",
    "# 0.0 360.3975 66.383875\n",
    "# 0.0 0.0 1.0\n",
    "\n",
    "# 425.0 2.5"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "vggt",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
